package com.fuhe.chen.vendingmachine.controller;

import com.alibaba.fastjson.JSON;
import com.fuhe.chen.vendingmachine.common.MachineCache;
import com.fuhe.chen.vendingmachine.dto.ApiResponse;
import com.fuhe.chen.vendingmachine.dto.ApiResponseForList;
import com.fuhe.chen.vendingmachine.common.Utils;
import com.fuhe.chen.vendingmachine.constant.MessageConstant;
import com.fuhe.chen.vendingmachine.dto.AdvertisementDto;
import com.fuhe.chen.vendingmachine.dto.CommodityInMachine;
import com.fuhe.chen.vendingmachine.dto.CommoditySalesVolumeData;
import com.fuhe.chen.vendingmachine.dto.cond.AdvertisementCond;
import com.fuhe.chen.vendingmachine.pojo.*;
import com.fuhe.chen.vendingmachine.service.*;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@Api(tags = "信息接口(面向售货机平板)")
public class ApiController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApiController.class);

    @Autowired
    IAdvertisementService advertisementService;

    @Autowired
    IMachineService machineService;

    @Autowired
    ICommodityService commodityService;

    @Autowired
    IItemService itemService;

    @Autowired
    IBookOrderService bookOrderService;

    @Autowired
    ICategoryService categoryService;

    @Autowired
    ICommoditySellLabelService sellLabelService;

    @Autowired
    IStatisticService statisticService;

    @Autowired
    IMQTTService imqttService;



    /**
     * 根据机器id查询售货机商品分类
     *
     * @param model
     * @param machineId
     * @return
     */
    @ApiOperation(value = "根据机器id查询售货机商品分类(新)", notes = "返回json格式数据")
    @GetMapping({"/machineApp/getItemCategories/{machineId}"})
    @ResponseBody
    public ApiResponseForList<Category> getItemCategories(Model model, @PathVariable int machineId) {

        List<Category> categories = itemService.queryCategories(machineId);

        ApiResponseForList<Category> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(MessageConstant.Success.SUCCESS_CODE);
        response.setMessage(MessageConstant.Success.QUERY_SUCCESS_MESSAGE);
        response.setData(categories);

        return response;
    }

    /**
     * 根据机器id查询待入货订单信息
     *
     * @param machineId
     * @return
     */
    @ApiOperation(value = "根据机器id查询待入货订单信息", notes = "返回json格式数据")
    @GetMapping({"/api/phone/getBookOrder/{machineId}"})
    @ResponseBody
    public ApiResponseForList<BookOrder> getBookOrder(@PathVariable int machineId) {

        List<BookOrder> bookOrders = bookOrderService.queryOrderByMachineId(machineId);

        ApiResponseForList<BookOrder> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(10000);
        response.setMessage("订单进货成功");
        response.setData(bookOrders);

        return response;
    }

    /**
     * 根据机器id返回不同的商品信息
     *
     * @param machineId
     * @return
     */
    @ApiOperation(value = "根据机器id和分类id返回不同的商品信息(新)")
    @GetMapping({"/machineApp/getItemsByCategory/{machineId}/{categoryId}"})
    @ResponseBody
    public ApiResponseForList<RelationshipItemMachine> getItemsByCategory(@PathVariable int machineId, @PathVariable int categoryId) {
        List<RelationshipItemMachine> relationships = itemService.queryItemByCategory(machineId, categoryId);
        ApiResponseForList<RelationshipItemMachine> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(MessageConstant.Success.SUCCESS_CODE);
        response.setMessage(MessageConstant.Success.QUERY_SUCCESS_MESSAGE);
        response.setData(relationships);

        return response;
    }

    /**
     * 根据机器id返回在售商品信息列表
     *
     * @param machineId
     * @return
     */
    @ApiOperation(value = "根据机器id返回在售商品信息列表")
    @GetMapping({"/machineApp/getItemListByMachine/{machineId}"})
    @ResponseBody
    public ApiResponseForList<RelationshipItemMachine> getItemListByMachine(@PathVariable int machineId) {
        List<RelationshipItemMachine> relationships = itemService.queryItemListByMachineID(machineId);
        ApiResponseForList<RelationshipItemMachine> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(MessageConstant.Success.SUCCESS_CODE);
        response.setMessage(MessageConstant.Success.QUERY_SUCCESS_MESSAGE);
        response.setData(relationships);

        return response;
    }



    @ApiOperation(value = "查询广告信息", notes = "返回json格式数据")
    @GetMapping({"/api/advertisement"})
    @ResponseBody
    public ApiResponseForList<AdvertisementDto> getAdvertisement() {
        AdvertisementCond advertisementCond = new AdvertisementCond();
        advertisementCond.setStatus(0);
        PageInfo<Advertisement> byCondition = advertisementService.findByCondition(advertisementCond, 1, 20);

        List<AdvertisementDto> advertisementDtos = new ArrayList<>();

        byCondition.getList().forEach(advertisement ->
                advertisementDtos.add(new AdvertisementDto(advertisement.getId(),
                        advertisement.getAdvertisement_name(),
                        advertisement.getPic_url())));

        ApiResponseForList<AdvertisementDto> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(10000);
        response.setMessage("调用成功");
        response.setData(advertisementDtos);

        return response;
    }

    @ApiOperation(value = "查询指定机器空余格子列表", notes = "返回json格式数据")
    @GetMapping({"/api/machine/emptyContainer/{machineId}"})
    @ResponseBody
    public ApiResponseForList<Container> getEmptyContainer(Model model, @PathVariable Integer machineId) {
        List<Container> containers = machineService.queryEmptyContainer(machineId);

        ApiResponseForList<Container> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(10000);
        response.setMessage("调用成功");
        response.setData(containers);

        return response;
    }

    @ApiOperation(value = "机器进货(售货机商品)(新)")
    @PostMapping({"/machineApp/addItemStock"})
    @ResponseBody
    public ApiResponseForList<String> addItemStock(
            @RequestParam(value = "machineID", required = true) Integer machineID,
            @RequestParam(value = "commodityID", required = true) Integer commodityID,
            @RequestParam(value = "containerNumber", required = true) String containerNumber) {


        String message = itemService.addStock(commodityID, machineID, containerNumber);

        ApiResponseForList<String> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(MessageConstant.Success.SUCCESS_CODE);
        response.setMessage(message);

        return response;
    }

    @ApiOperation(value = "机器进货(客户预约单)")
    @PostMapping({"/api/machine/addBookCommodity"})
    @ResponseBody
    public ApiResponseForList<String> addBookCommodity(Model model,
                                                       @RequestParam(value = "machineID", required = true) Integer machineID,
                                                       @RequestParam(value = "bookOrderID", required = true) String bookOrderID,
                                                       @RequestParam(value = "containerNumber", required = true) String containerNumber) {


        String message = bookOrderService.addOrderCommodity(machineID, bookOrderID, containerNumber);


        ApiResponseForList<String> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(MessageConstant.Success.SUCCESS_CODE);
        response.setMessage(message);

        return response;
    }

    @ApiOperation(value = "查询商品销售信息", notes = "返回json格式数据")
    @GetMapping("/api/statistic/commoditySalesVolumeData")
    @ResponseBody
    public String getCommoditySalesVolumeData() {
        List<CommoditySalesVolumeData> commoditySalesVolumeData = statisticService.CommoditySalesVolumeData();
        String result = JSON.toJSON(commoditySalesVolumeData).toString();
        return result;
    }

    /**
     * 查询所有商品信息列表(商城APP)
     */
    @ApiOperation(value = "查询所有商品信息", notes = "返回json格式数据")
    @GetMapping("api/getCommodityList")
    @ResponseBody
    public ApiResponseForList<Commodity> getCommodityList() {
        List<Commodity> commodities = commodityService.queryAllOnSale();

        ApiResponseForList<Commodity> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(10000);
        response.setMessage("调用成功");
        response.setData(commodities);
        return response;
    }

    /**
     * 查询所有商品信息列表(售货机)
     */
    @ApiOperation(value = "查询所有商品信息(新)", notes = "返回json格式数据")
    @GetMapping("machineApp/getItemList")
    @ResponseBody
    public ApiResponseForList<Item> getItemList() {
        List<Item> items = itemService.queryAllOnSale();

        ApiResponseForList<Item> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(10000);
        response.setMessage("调用成功");
        response.setData(items);
        return response;
    }


    @ApiOperation(value = "获取全部商品分类", notes = "返回json格式数据")
    @GetMapping({"api/getCategories"})
    @ResponseBody
    public ApiResponseForList<Category> getCategories() {
        List<Category> all = categoryService.findAll();

        ApiResponseForList<Category> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(10000);
        response.setMessage("调用成功");
        response.setData(all);
        return response;
    }

    @ApiOperation(value = "按预约单id取货")
    @PostMapping({"api/pickUpOrder"})
    @ResponseBody
    public ApiResponse<String> pickUpOrder(@RequestParam("orderId") String orderId,
                                           @RequestParam("orderCode") String orderCode) {
        ApiResponse<String> response = new ApiResponse<>();

        String encode = Utils.MD5encode(orderId);
        if (orderCode.equals(encode)) {
            BookOrder bookOrder = bookOrderService.queryOrderByOrderId(orderId);
            if (bookOrder != null && bookOrder.getOrder_status() == 2) {
                bookOrderService.takeBookOrderCommodity(bookOrder);
                imqttService.sendMessageForPick(bookOrder);

                //机器容量加1
                MachineCache.addCapacity(bookOrder.getMachine_id());

                response.setSuccess(true);
                response.setCode(10000);
                response.setMessage("取货成功");
            } else {
                response.setCode(15555);
                response.setMessage("取货失败,未找到订单");
            }
        } else {
            response.setCode(14444);
            response.setMessage("取货失败,加密认证错误");
        }
        response.setSuccess(false);
        return response;
    }
}
